<template>
  <div class="simple-date-picker">
    <van-field
      :model-value="displayValue"
      :label="label"
      :placeholder="placeholder"
      readonly
      is-link
      @click="showPicker = true"
    />
    
    <van-popup v-model:show="showPicker" position="bottom">
      <van-date-picker
        :model-value="pickerValue"
        :title="title"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  label: {
    type: String,
    default: '日期'
  },
  placeholder: {
    type: String,
    default: '请选择日期'
  },
  title: {
    type: String,
    default: '选择日期'
  }
})

const emit = defineEmits(['update:modelValue'])

const showPicker = ref(false)

// 显示值（格式化后的日期字符串）
const displayValue = computed(() => {
  if (!props.modelValue) return ''
  return props.modelValue
})

// 选择器值（字符串数组，确保传入 van-date-picker 格式一致）
const pickerValue = ref([])

// 监听外部值变化，更新选择器值（手动解析，避免时区偏移）
watch(() => props.modelValue, (newValue) => {
  if (newValue && /^\d{4}-\d{2}-\d{2}$/.test(newValue)) {
    const [y, m, d] = newValue.split('-')
    pickerValue.value = [y, m, d]
  } else {
    const today = new Date()
    const y = String(today.getFullYear())
    const m = String(today.getMonth() + 1).padStart(2, '0')
    const d = String(today.getDate()).padStart(2, '0')
    pickerValue.value = [y, m, d]
  }
}, { immediate: true })

// 确认选择（兼容 Vant 返回结构）
const onConfirm = (value) => {
  // Vant 可能返回 { selectedValues: ['2025','09','01'], selectedOptions, selectedIndexes }
  let y, m, d

  if (value && Array.isArray(value.selectedValues)) {
    ;[y, m, d] = value.selectedValues
  } else if (Array.isArray(value)) {
    ;[y, m, d] = value.map(v => String(v).padStart(2, '0'))
    if (y && y.length === 2) {
      // 兜底：如果误把年当成两位数，回退到当前 picker 值
      ;[y, m, d] = pickerValue.value
    }
  } else {
    ;[y, m, d] = pickerValue.value
  }

  const dateStr = `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`
  emit('update:modelValue', dateStr)
  showPicker.value = false
}
</script>

<style scoped>
.simple-date-picker {
  width: 100%;
}
</style>
